﻿using Alert_Form.Component.Alert;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YXChatFormClient.Utility
{
    public class HttpHelper
    {
        private static readonly object LockObj = new object();
        private static HttpClient client = null;
        public static readonly string BASE_ADDRESS = Api.ServerUrl;
        public HttpHelper()
        {
            GetInstance();
        }
        /// <summary>
        /// 制造单例
        /// </summary>
        /// <returns></returns>
        public static HttpClient GetInstance()
        {
            if (client == null)
            {
                lock (LockObj)
                {
                    if (client == null)
                    {
                        client = new HttpClient()
                        {
                            BaseAddress = new Uri(BASE_ADDRESS),
                        };
                        client.DefaultRequestHeaders.Connection.Add("keep-alive");
                        //帮HttpClient热身
                        client.SendAsync(new HttpRequestMessage
                        {
                            Method = new HttpMethod("HEAD"),
                            RequestUri = new Uri(BASE_ADDRESS)
                        }).Result.EnsureSuccessStatusCode();
                    }
                }
            }
            return client;
        }
        /// <summary>
        /// 同步Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public string Post(string url, string strJson)
        {
            try
            {
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //client.DefaultRequestHeaders.Connection.Add("keep-alive");
                //由HttpClient发出Post请求
                Task<HttpResponseMessage> res = client.PostAsync(url, content);
                if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string resMsgStr = res.Result.Content.ReadAsStringAsync().Result;
                    return resMsgStr;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="strJson">传入的数据</param>
        /// <returns></returns>
        public async Task<string> PostAsync(string url,string strJson)
        {
            try
            {
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage res = await client.PostAsync(url,content);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string resMsgStr = await res.Content.ReadAsStringAsync();
                    return resMsgStr;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        
        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="TResult">返回参数的数据类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="data">传入的数据</param>
        /// <returns></returns>
        public async Task<TResult> PostAsync<TResult>(string url, object data)
        {
            try
            {
                var jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage res = await client.PostAsync(url, content);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string resMsgStr = await res.Content.ReadAsStringAsync();
                    var result= JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);
                    if (result != null && result.Success) 
                    {
                        return result.Data;
                    }
                    AlertForm.ShowAlert(result.Msg,AlertType.Error,5);
                    return default;
                }
                else
                {
                    MessageBox.Show(res.StatusCode.ToString());
                    return default;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return default;
            }
        }
        /// <summary>
        /// 同步Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public string Get(string url)
        {
            try
            {
                var responseString = client.GetStringAsync(url);
                return responseString.Result;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public async Task<string> GetAsync(string url)
        {
            try
            {
                var responseString =await client.GetStringAsync(url);
                return responseString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <typeparam name="TResult">返回参数的数据</typeparam>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public async Task<TResult> GetAsync<TResult>(string url)
        {
            try
            {
                var resMsgStr = await client.GetStringAsync(url);
                var result = JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);
                if (result != null && result.Success)
                {
                    return result.Data;
                }
                AlertForm.ShowAlert(result.Msg,AlertType.Error,5);
                return default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return default(TResult);
            }
        }

    }

    public class ResultDto<TResult>
    {
        public string Msg { get; set; }
        public TResult Data { get; set; }
        public bool Success { get; set; }
    }

    public static class Api
    {
        static Api()
        {
            ServerUrl = JSONHelper.ReadJSON<string>("ServerUrl");
        }
        /// <summary>
        /// 服务器地址
        /// </summary>
        public static readonly string ServerUrl;
        /// <summary>
        /// 查询账号信息 GET
        /// </summary>
        public const string GetAccountByNumber = "api/account/GetAccountByNumber";
        /// <summary>
        /// 注册 POST
        /// </summary>
        public const string AccountRegister = "api/account/register";
        /// <summary>
        /// 登录 POST
        /// </summary>
        public const string AccountLogin = "api/account/login";
        /// <summary>
        /// 搜索好友 POST
        /// </summary>
        public const string SearchBuddyInfo = "api/buddy/SearchBuddyInfo";
        /// <summary>
        /// 创建或修改好友关系
        /// </summary>
        public const string CreateOrUpdateBuddy = "api/buddy/CreateOrUpdateBuddy";
        /// <summary>
        /// Get 需要selfNumber参数
        /// </summary>
        public const string GetNewBuddys = "api/buddy/GetNewBuddys";
        /// <summary>
        /// Get 需要selfNumber参数
        /// </summary>
        public const string GetBuddys = "api/buddy/GetBuddys";
        /// <summary>
        /// 创建聊天记录 POST
        /// </summary>
        public const string CreateChatRecord = "api/ChatRecord/CreateChatRecord";
        /// <summary>
        /// Get 需要selfNumber参数 
        /// </summary>
        public const string GetChatRecordAll = "api/ChatRecord/GetChatRecordAll";
        /// <summary>
        /// Get 需要selfNumber参数 buddyNumber参数
        /// </summary>
        public const string GetChatRecord = "api/ChatRecord/GetChatRecord";
        /// <summary>
        /// POST 修改账户头像
        /// </summary>
        public const string UpdateAccountAvatar = "api/Account/UpdateAccountAvatar";
        /// <summary>
        /// POST 修改账户信息
        /// </summary>
        public const string UpdateAccount = "api/Account/UpdateAccount";
        /// <summary>
        /// GET 获取用户密码
        /// </summary>
        public const string GetAccountPwd = "api/Account/GetAccountPassWord";

    }
}